package com.cn.task;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cn.bean.SimpleMap;
import com.cn.dao.JdbcDao;
import com.cn.dao.SqlParam;
import com.cn.exception.MyException;
import com.cn.xc.utils.CollectionUtil;
import com.cn.xc.utils.StringUtil;

/**
 * @author Leezy Description ：
 * 
 *         modified by sushy
 */
public class DefaultLogicService implements ITaskLogicService {

	protected Log logger = LogFactory.getLog(getClass());

	protected JdbcDao jdbcDao;

	public void setJdbcDao(JdbcDao jdbcDao) {
		this.jdbcDao = jdbcDao;
	}

	public Object run(Object... args) {

		if (args.length < 1) {
			logger.error( "定时任务内容启动参数不能为空！");
			throw new MyException("定时任务内容启动参数不能为空！");
		}

		SimpleMap param = new SimpleMap();
		if (args.length > 0) {
			param = (SimpleMap) args[0];
		}

		String taskName = param.getString("taskName");
		String fileNameCons = param.getString("fileNameCons");

		String fileName = CtgFileService.getFileName(fileNameCons, param);
		String filePath = param.getString("filePath");

		// # 做特殊处理
		if ("spec".equals(taskName)) {

		} else {
			long rownum = 0;
			File localCityFile = null;
			FileOutputStream fs = null;
			OutputStreamWriter os = null;
			try {
				// 创建临时文件
				localCityFile = CtgFileService.getFile(filePath, fileName);
				CtgFileService.createNewFile(localCityFile);
				param.put("currentFileName", localCityFile.getName());
				fs = new FileOutputStream(localCityFile);
				os = new OutputStreamWriter(fs, param.getString("charsetName"));

				@SuppressWarnings("unchecked")
				List<String> qrySqls = (List<String>) param.get("qrySqls");
				for (String qrySql : qrySqls) {
					param.set("qrySql", qrySql);
					rownum += loadDataDefault(os, param);
				}

			} catch (IOException e) {
				e.printStackTrace();
				logger.error("Gen File " + localCityFile.getAbsoluteFile() + "生成" + fileName + "文件失败!");
				throw new RuntimeException("生成" + fileName + "文件失败!", e);
			} catch (Exception t) {
				t.printStackTrace();
				logger.error("Gen File " + localCityFile.getAbsoluteFile() + "生成" + fileName + "文件失败!");
				throw new RuntimeException("生成" + fileName + "文件失败!", t);
			} finally {
				IOUtils.closeQuietly(os);
				IOUtils.closeQuietly(fs);
			}

			SimpleMap resultMap = new SimpleMap();
			resultMap.put("rownum", rownum);
			resultMap.put("fileName", localCityFile.getName());
			resultMap.put("filePath", localCityFile.getPath());
			resultMap.put("absoluteFile", localCityFile.getAbsoluteFile());

			return resultMap;
		}

		return null;
	}

	/**
	 * //# 加载数据
	 * 
	 * @param output
	 * @param param
	 * @return
	 */
	protected long loadDataDefault(OutputStreamWriter output, SimpleMap param) {

		String qrySql = param.getString("qrySql");
		String sqlCon = param.getString("sqlCon");
		String platCode = param.getString("platCode");
		System.out.println("platCode:" + platCode);

		//# sql传递过来的参数
		if (qrySql.contains("{#platCode#}")) {
			qrySql = qrySql.replace("{#platCode#}", platCode);
		}

		if (StringUtil.isNotEmpty(sqlCon)) {
			String[] cons = StringUtil.splitTokens(sqlCon, ",");
			for (String condition : cons) {
				String[] conDetails = StringUtil.splitTokens(condition, "~");
				if (conDetails.length > 1) {
					if ("limitLine".equals(conDetails[0])) {
						qrySql += " and rownum < " + conDetails[1];
					}
				}
			}
		}

		SqlParam sqlParam = new SqlParam();
		sqlParam.addSql(qrySql);

		String colSeparator = param.getString("colSeparator");
		String rowSeparator = param.getString("rowSeparator");
		int columnAmount = param.getInt("columnAmount");
		if (StringUtil.isEmpty(colSeparator)) {
			colSeparator = "|#%#|";
		}
		if (StringUtil.isEmpty(rowSeparator)) {
			rowSeparator = "\r\n";
		}

		RowToFile rch = new RowToFile(output, colSeparator, rowSeparator, columnAmount);

		jdbcDao.query(sqlParam, rch);
		try {
			output.flush();
		} catch (IOException e) {
			logger.error("---加载数据失败！" + e);
			e.printStackTrace();
		}

		// # 处理文件内容为空的情况
		long resultNum = rch.getRowNum();
		if (resultNum < 1) {
			logger.warn("---文件"+param.getString("currentFileName")+" 数据为空，写入默认值。");
			return writeDefualtValue(output, param, resultNum);
		}

		return resultNum;
	}

	/**
	 * //# 文件为空时，写入默认配置
	 * 
	 * @param output
	 * @param param
	 * @param resultNum
	 * @return
	 */
	private long writeDefualtValue(OutputStreamWriter output, SimpleMap param, long resultNum) {
		String mustContent = param.getString("isMustUpload");
		if (StringUtil.isNotEmpty(mustContent)) {
			try {
				output.write(mustContent);
				return resultNum + 1;
			} catch (IOException e) {
				logger.error("文件内容为空时，写入默认值失败!" + e);
				System.out.println("文件内容为空时，写入默认值失败!");
				e.printStackTrace();
			}
		}
		return 0L;
	}

	protected int toInt(String str) {
		return NumberUtils.toInt(str);
	}

	protected long toLong(String str) {
		return NumberUtils.toLong(str);
	}

	protected long toLong(String str, long defVal) {
		return NumberUtils.toLong(str, defVal);
	}

	protected boolean isEmpty(String str) {
		return StringUtil.isEmpty(str);
	}

	protected boolean isNotEmpty(String str) {
		return !StringUtil.isEmpty(str);
	}

	protected boolean isEmpty(Collection<?> collection) {
		return CollectionUtil.isEmpty(collection);
	}

	protected boolean isNotEmpty(Collection<?> collection) {
		return CollectionUtil.isNotEmpty(collection);
	}

	protected static <T> T getFirst(Collection<T> collection) {
		return CollectionUtil.getFirst(collection);
	}

	protected static String[] splitTokens(String str, String sep) {
		return StringUtil.splitTokens(str, sep);
	}

	protected static String[] split(String str, String regex) {
		if (str == null) {
			return null;
		}
		return str.split(regex);
	}

	protected boolean isEmpty(Map<?, ?> map) {
		return map == null || map.isEmpty();
	}

	protected boolean isNotEmpty(Map<?, ?> map) {
		return map != null && !map.isEmpty();
	}

}
